package com.epam.android.mailcomponent.contacts;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.epam.android.mailcomponent.R;

public class ContactsActivity extends ListActivity {

	public static final String CONTACTS_LIST_EXTRA_NAME = "contacts";

	private Button buttonOk;
	private Button buttonCancel;
	private List<Contact> contactsList;
	private ContactsAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts_activity);
		initListFromContacts();
		initButtons();
		initListView();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Contact contact = contactsList.get(position);
		contact.setChecked(!contact.isChecked());
		adapter.notifyDataSetChanged();
	}

	private void initButtons() {
		// button ok
		buttonOk = (Button) findViewById(R.id.contacts_button_ok);
		buttonOk.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				ArrayList<String> chosenEmails = new ArrayList<String>();
				for (Contact contact : contactsList) {
					if (contact.isChecked()) {
						chosenEmails.add(contact.getEmail());
					}
				}
				intent.putExtra(CONTACTS_LIST_EXTRA_NAME, chosenEmails);
				setResult(RESULT_OK, intent);
				finish();
			}
		});

		// button cancel
		buttonCancel = (Button) findViewById(R.id.contacts_button_cancel);
		buttonCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private void initListView() {
		adapter = new ContactsAdapter(this, contactsList);
		setListAdapter(adapter);
		adapter.notifyDataSetChanged();
	};
	
	private void initListFromContacts() {
		contactsList = new ArrayList<Contact>();
		Cursor cursor = getContentResolver().query(
				Email.CONTENT_URI, new String[] {Email.DATA, Contacts.DISPLAY_NAME}, 
				null, null, null);
		if (cursor.moveToFirst()) {
			while (!cursor.isAfterLast()) {
				String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
				String email = cursor.getString(cursor.getColumnIndex(Email.DATA));
				contactsList.add(new Contact(name, email, false));
				cursor.moveToNext();
			}
		}
	}
}
